/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package at.irian.web.jsf.orchestra;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Manfred Geiler
 */
class TransactionTokenContainer implements Serializable
{
    private static final long serialVersionUID = 7785970863015542534L;

    private String previous;
    private List<String> previousTokens = new LinkedList<String>();
    private String token;
    private static final int MAX_ELEMENT_COUNT = 10;

    public void setToken(String token)
    {
        if (previous != null)
        {
            previousTokens.add(previous);
            if (previousTokens.size() > MAX_ELEMENT_COUNT)
            {
                previousTokens.remove(0);
            }
        }
        previous = this.token;
        this.token = token;
    }

    public String getToken()
    {
        return token;
    }

    public RequestType checkToken(String tokenToCheck)
    {
        if (tokenToCheck.equals(token))
        {
            return RequestType.NORMAL;
        }
        if (tokenToCheck.equals(previous))
        {
            return RequestType.DOUBLE_SUBMIT_OR_RELOAD;
        }
        if (previousTokens.contains(tokenToCheck))
        {
            return RequestType.BROWSER_BACK;
        }
        return RequestType.UNKNOWN;
    }

    public String toString()
    {
        return "TransactionTokenContainer{" +
                "previousTokens='" + previousTokens + '\'' +
                ", previous='" + previous + '\'' +
                ", token='" + token + '\'' +
                '}';
    }
}
